# PS:好比特下单价格只能是整数，不然会出错；好比特的请求数据为固定格式，次序不能改；
# 请求的数据格式不正确就会产生http错误，如HTTP Error 400: Bad Request
from lib.utilHaobtc import request, getDepth
from lib.settings import HAOBTC_API_URL
import config


class Haobtc(object):
    def __init__(self):
        self.__apikey = config.HAOBTC_API_KEY
        self.fee = HAOBTC_API_URL['fee']

        self.btc_free = 0.0  # 账户情况
        self.btc_frozen = 0.0
        self.cny_free = 0.0
        self.cny_frozen = 0.0

        self.bid = 0.0  # 买一卖一情况
        self.bid_volume = 0.0
        self.ask = 0.0
        self.ask_volume = 0.0

    def update_depth(self):
        # 更新深度之前，先将上一次的深度置零
        self.bid = 0.0
        self.bid_volume = 0.0
        self.ask = 0.0
        self.ask_volume = 0.0
        try:
            params = {}
            params['api_key'] = self.__apikey
            params['size'] = 1
            response = getDepth(HAOBTC_API_URL['depth'], params)
            if not response:
                return False
            if response and 'code' in response:
                return False
            self.bid = float(response['bids'][0][0])
            self.bid_volume = float(response['bids'][0][1])
            self.ask = float(response['asks'][0][0])
            self.ask_volume = float(response['asks'][0][1])
            return True
        except Exception as e:
            print(self.__class__.__name__ + ' update_depth error: ' + str(e))
            return False

    def update_accountInfo(self):
        # 更新账户资产之前，先将之前的置零
        self.btc_free = 0.0
        self.btc_frozen = 0.0
        self.cny_free = 0.0
        self.cny_frozen = 0.0
        try:
            params = {}
            params['api_key'] = self.__apikey
            response = request(HAOBTC_API_URL['account_info'], params)
            if not response:
                return False
            if response and 'code' in response:
                return False
            self.btc_free = float(response['exchange_btc'])
            self.btc_frozen = float(response['exchange_frozen_btc'])
            self.cny_free = float(response['exchange_cny'])
            self.cny_frozen = float(response['exchange_frozen_cny'])
            return True
        except Exception as e:
            print(self.__class__.__name__ + ' update_accountInfo error: ' + str(e))
            return False

    def buy(self, price, amount):
        try:
            # 使用“限价单”的方式挂单
            params = {"api_key": self.__apikey, "amount": amount, "type": "buy", "price": price}
            response = request(HAOBTC_API_URL['trade'], params)
            if not response:
                return False
            if response and 'code' in response:
                return False
            if response['order_id'] == (-1 or '-1'):
                return False
            return str(response['order_id'])
        except Exception as e:
            print(self.__class__.__name__ + 'buy error: ' + str(e))
            return False

    def buy_maker_only(self, price, amount):
        try:
            # 使用“现价只挂单”的方式挂单，不用担心吃单的问题
            params = {"api_key": self.__apikey, "amount": amount, "type": "buy_maker_only", "price": price}
            response = request(HAOBTC_API_URL['trade'], params)
            if not response:
                return False
            if response and 'code' in response:
                return False
            if response['order_id'] == (-1 or '-1'):
                return False
            return str(response['order_id'])
        except Exception as e:
            print(self.__class__.__name__ + 'buy error: ' + str(e))
            return False

    def sell(self, price, amount):
        try:
            # 使用“限价单”的方式挂单
            params = {"api_key": self.__apikey, "amount": amount, "type": "sell", "price": price}
            response = request(HAOBTC_API_URL['trade'], params)
            if not response:
                return False
            if response and 'code' in response:
                return False
            if response['order_id'] == (-1 or '-1'):
                return False
            return str(response['order_id'])
        except Exception as e:
            print(self.__class__.__name__ + ' sell error: ' + str(e))
            return False

    def sell_maker_only(self, price, amount):
        try:
            # 使用“现价只挂单”的方式挂单，不用担心吃单的问题
            params = {"api_key": self.__apikey, "amount": amount, "type": "sell_maker_only", "price": price}
            response = request(HAOBTC_API_URL['trade'], params)
            if not response:
                return False
            if response and 'code' in response:
                return False
            if response['order_id'] == (-1 or '-1'):
                return False
            return str(response['order_id'])
        except Exception as e:
            print(self.__class__.__name__ + ' sell error: ' + str(e))
            return False

    def order_info(self, orderId):
        try:
            if orderId == False:
                return False
            params = {"api_key": self.__apikey, "order_id": orderId}
            response = request(HAOBTC_API_URL['order_info'], params)
            if not response:
                return False
            if response and 'code' in response:
                return False
            if response['status'] in ('PENDING', 'SUBMIT', 'OPEN'):
                return {'status': 'cancelable', 'amount': response['amount'], 'side': response['side'], 'price': response['price']}
            else:
                return {'status': 'ircancelable', 'amount': response['amount'], 'side': response['side'], 'price': response['price']}
        except Exception as e:
            print(self.__class__.__name__ + ' order_info error: ' + str(e))
            return False

    def get_orders(self):
        try:
            params = {}
            params['api_key'] = self.__apikey
            response = request(HAOBTC_API_URL['get_orders'], params)
            if not response:
                return False
            if response and 'code' in response:
                return False
            return response
        except Exception as e:
            print(self.__class__.__name__ + ' get_orders error: ' + str(e))
            return False

    def cancel_order(self, orderId):
        try:
            if orderId == False:
                return False
            params = {"api_key": self.__apikey, "order_id": orderId}
            response = request(HAOBTC_API_URL['cancel_order'], params)
            if not response:
                return False
            if response and 'code' in response:
                return False
            if 'order_id' in response:
                return True
            else:
                return False
        except Exception as e:
            print(self.__class__.__name__ + ' cancel_order error: ' + str(e))
            return False

    def cancel_all(self):
        response = self.get_orders()
        if not response:
            return False
        for order in response:
            self.cancel_order(order['order_id'])
